package com.adopapa.wechatapi.util;

import java.nio.charset.Charset;
import java.security.MessageDigest;

public class MD5Util {
    private final static String[] hexDigits = {"0", "1", "2", "3", "4", "5", "6", "7",
            "8", "9", "a", "b", "c", "d", "e", "f"};
    /**
     * 转换字节数组为16进制字串
     * @param b 字节数组
     * @return 16进制字串
     */
    public static String byteArrayToHexString(byte[] b) {
        StringBuilder resultSb = new StringBuilder();
        for (byte aB : b) {
            resultSb.append(byteToHexString(aB));
        }
        return resultSb.toString();
    }
    /**
     * 转换byte到16进制
     * @param b 要转换的byte
     * @return 16进制格式
     */
    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0) {
            n = 256 + n;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }
    /**
     * MD5编码
     * @param origin 原始字符串
     * @return 经过MD5加密之后的结果
     */
    public static String MD5Encode(String origin) {
        String resultString = null;
        try {
            resultString = origin;
            MessageDigest md = MessageDigest.getInstance("MD5");
            resultString = byteArrayToHexString(md.digest(resultString.getBytes(Charset.forName("UTF-8"))));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultString;
    }
    
    public static void main(String[] args) {
	    String source = "appid=wx895f45111dcf1cdf&body=22222&mch_id=1233225902&nonce_str=3fefdfd537b3483e8c4e9c93430099a6&notify_url=http://www.diangang.com/app/payment/notifyUrl4Wechat.do&openid=o4l_ejqMxvywHw8wUBKJFYnSVQgU&out_trade_no=5f54c1a4561b4f0eb9007f81270289b7&spbill_create_ip=127.0.0.1&total_fee=76800&trade_type=JSAPI&key=ff64ff2ad9da0459ff44bd653d2f746f";
	    System.out.println(MD5Encode(source));
}
}